package com.epam.traning.taskmanager.xml;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;

import com.epam.traning.taskmanager.xml.XmlParser.IXmlHandler;
import com.epam.traning.taskmanager.xml.bo.App;

public class AppsHandler implements IXmlHandler<List<App>> {

	private static final String ATTR_ORDER = "order";

	private static final String TAG_DESCRIPTION = "description";

	private static final String TAG_NAME = "name";

	private static final String TAG_APPLICATION = "application";
	
	private List<App> listApps;
	
	private App currentApp;
	
	@Override
	public void startDocument() {
		
	}

	@Override
	public void startTag(String tagName, Attributes atts) {
		if (tagName.equalsIgnoreCase(TAG_APPLICATION)) {
			currentApp = new App();
			String value = atts.getValue(ATTR_ORDER);
			currentApp.setOrder(Integer.valueOf(value));
		}
	}

	@Override
	public void endTag(String tagName, String value) {
		if (currentApp != null) {
			if (tagName.equalsIgnoreCase(TAG_APPLICATION)) {
				if (listApps == null) {
					listApps = new ArrayList<App>();
				}
				listApps.add(currentApp);
				currentApp = null;
			} else if (tagName.equalsIgnoreCase(TAG_NAME)) {
				currentApp.setName(value);
			} else if (tagName.equalsIgnoreCase(TAG_DESCRIPTION)) {
				currentApp.setDescription(value);
			}
		}
	}

	@Override
	public List<App> getResult() {
		return listApps;
	}

}
